import { Command } from 'commander'
import { Branches } from './branches'
import { GitStatus } from './git/git-status'
import { git } from './git/git'

export function cmX(program: Command) {
  const br = new Branches()

  program
    .command('x')
    .description('快速创建修复分支')
    .argument('<branchName>', '修复分支名提示')
    .argument('[base]', '基地分支')
    .option('-a, --add', '添加功能的分支')
    .action((content: string, base: string, opt: { add: boolean }) => {
      // 例如：MLSIPL-4035，sharing
      if (content.match(/^[a-zA-Z_\-0-9]+$/)) {
        const baseBranch = br.getBaseBranch(base)
        if (!baseBranch) {
          console.log("can't find base branch!")
          return
        }

        const status = new GitStatus()
        let needStash = false
        if (status.hasNotStaged()) {
          if (status.hasStaged()) {
            console.log(
              'Some changed not staged yet! Reset Checkout will make change lost!',
            )
            return
          } else {
            needStash = true
          }
        } else {
          if (status.hasChanged()) {
            needStash = true
          }
        }

        const matched = baseBranch.match(
          /^(testing|feature|debug)\/([.0-9a-zA-Z_]+)/,
        )
        if (matched) {
          if (needStash) {
            git.addAll()
            git.stashPush()
          }

          const version = matched[2]
          const toFixBranch = `${opt.add ? 'add' : 'fix'}/${version}-${content}`

          const cur = git.currentBranch()
          if (cur == baseBranch) {
            br.checkoutBranch(toFixBranch, false)
          } else {
            br.checkoutBranchWithBaseBranch(toFixBranch, baseBranch, false)
          }
          if (needStash) {
            git.stashPop()
          }
        } else {
          console.log('base branch is not fixing target', baseBranch)
        }
      } else {
        console.log('...')
      }
    })
}
